package com.digital.welcome.Realm;


import com.digital.welcome.entity.User;
import com.digital.welcome.service.PermissionService;
import com.digital.welcome.service.RoleService;
import com.digital.welcome.service.UserService;
import com.digital.welcome.token.JwtToken;
import com.digital.welcome.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("————权限认证————");
        String username = (String) principalCollection.iterator().next();
        Set<String> roleNames = roleService.selectAllRoleNamesByUsername(username);
        Set<String> permission = permissionService.selectAllPermissionCodeByUsername(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleNames);
        info.setStringPermissions(permission);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("————身份认证————");
        //这个authenticationToken就是从过滤器中传⼊的jwtToken
        JwtToken jwtToken = (JwtToken) authenticationToken;
        String token = (String) jwtToken.getPrincipal();
        if (token == null) {
            throw new NullPointerException("jwtToken 不允许为空");
        }
        Claims claims = JwtUtil.parseJWT(token);
        assert claims != null;
        String username = claims.getId();

        User user = userService.getUserByUsername(username);
        log.info("在使⽤token登录"+username);
        if (user == null) {
            return null;
        }
        // 根据用户的情况，来构建 AuthenticationInfo 对象并返回；通常使用的实现类为: SimpleAuthenticationInfo；
        return new SimpleAuthenticationInfo(username, user.getUserPassword(), getName());
    }
}


